package com.etc.myblog.ser;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.MultipartStream;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

public class UploadImgSer extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		doPost(request, response);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		
		//获取服务器中项目根目录
		String savePath =     
				  request.getServletContext().getRealPath("/postImg");
		java.io.File uploadDir = new java.io.File(savePath);
		//如果此目录不存在，新建该目录
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        
		//新建一个SmartUpload，因form使用了multipart/form-data
		//所以值变成二进制数据，request无法获取，故需要用此类获取值
		SmartUpload su = new SmartUpload();
		 // 上传初始化
		  su.initialize(this.getServletConfig(),request,response);
		  //设置上传限制
		  // 限制每个上传文件的最大长度。
		  su.setMaxFileSize(1024*1024*1024*3);
		  // 限制总上传数据的长度。
		  su.setTotalMaxFileSize(1024*1024*1024*5);
		  // 设定允许上传的文件类型（扩展名）
		  // 禁止上传的文件类型（扩展名）,禁止上传exe和无扩展名的文件。
		try {
			  // 上传文件
			  su.upload();
		} catch (SmartUploadException e) {
			System.out.println(e.getMessage());
			return;
			// TODO: handle exception
		}
		
		//获取刚上传的文件
		File file = su.getFiles().getFile(0);
		//获取文件名
		String imgName = file.getFileName();
		//获取文件后缀
		String prefix=imgName.substring(imgName.lastIndexOf(".")+1);
		
		//文件名如果为空表示没有图片
		if( imgName.equals("")) {
			request.setAttribute("err", "请选择图片");
			request.getRequestDispatcher("inc/uploadImg.jsp").forward(request, response);
			return;
		}
		//后缀名不正确，不能上传
		if (!prefix.equals("jpg")&&!prefix.equals("gif")&&!prefix.equals("png")&&!prefix.equals("bmp")) {
			request.setAttribute("err", "图片格式错误");
			request.getRequestDispatcher("inc/uploadImg.jsp").forward(request, response);
			return;
		}
		//保存上传
		 if (!su.getFiles().getFile(0).isMissing()) {
			  try {
				su.save(savePath);
				String serimgPath = "/postImg/";
				String imPath = serimgPath + imgName;
				request.setAttribute("url", imPath);
				request.setAttribute("err", "图片上传成功");
				request.getRequestDispatcher("inc/uploadImg.jsp").forward(request, response);
			} catch (SmartUploadException e) {
				System.out.println(e.getMessage());
				// TODO: handle exception
			}
		  }
		
	}

}
